<template>
  <div class="table-box">
    <ProTable ref="proTable" title="用户列表" :columns="columns" :request-api="getTableList" :init-param="initParam"
      :data-callback="dataCallback" rowKey="userId">
      <!-- 自定义表格外，上面区域样式 -->
      <template #tableHeader>
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="addUser"> 新增用户 </el-button>
      </template>
      <!-- 单独定义某一个表头的样式 prop+'Header'-->
      <template #usernameHeader="scope">
        {{ scope.column.label + 'q(≧▽≦q)' }}
      </template>
      <!-- 自定义某一prop的列 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View"> 查看 </el-button>
        <el-button type="primary" link :icon="Delete"> 删除 </el-button>
      </template>
    </ProTable>
  </div>
</template>
<script setup lang="tsx" name="UseProTable">
// 基础表格+form+分页，分页与接口部分待优化 
import ProTable from "@/components/ProTable/index.vue";
import { ref, reactive, onBeforeUnmount, onBeforeMount } from "vue";
import { User } from "@/api/interface/index";
import { ElMessage, ElMessageBox } from "element-plus";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh } from "@element-plus/icons-vue";
import { getUserListAPI, getGenderOptionsAPI, addUserAPI } from "@/api/modules/user";

//获取表格数据
const getTableList = async (params?: any) => {
  // let newParams = JSON.parse(JSON.stringify(params));
  // newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  // newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  // delete newParams.createTime;
  let res = await getUserListAPI();
  return res;
};
const addUser = async () => {
  await addUserAPI({
    userId: "1",
    username: "小*",
    gender: "1",
    user: { detail: { age: "21" } },
    idCard: "410323",
    email: "17718558692@163.com",
    address: "北京",
    status: "1",
    createTime: "2023-10-10",
  })
  //initParam更改才会刷新表格
  initParam.a++
}
onBeforeMount(()=>{
  console.log(111)
})
onBeforeUnmount(()=>{
  console.log(444)
})

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ a: 1 });
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  console.log(data, 'ppp');
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};


// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();
// 表格配置项，其中User.ResUserList为tableData的ts类型
const columns: ColumnProps<User.ResUserList>[] = [
  { type: "selection", fixed: "left", width: 80 },
  { type: "index", label: "#", width: 80 },
  { type: "expand", label: "Expand", width: 100 },
  {
    prop: "username",
    label: "用户姓名",
    //带search表示其作为搜索参数，
    search: { el: "input" },
    //除了表格用具名插槽写法，也可以jsx来自定义render函数定义每列的样式
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
          {scope.row.username}
        </el-button>
      );
    }
  },
  {
    prop: "gender",
    label: "性别",
    // 获取下拉框options，字典请求不带参数情况
    enum: getGenderOptionsAPI,
    // 字典请求携带参数
    // enum: () => getUserGender({ id: 1 }),
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "label", value: "value" }
  },
  {
    // 多级 prop
    prop: "user.detail.age",
    label: "年龄",
    search: {
      // 自定义 search 显示内容，vModel_trim=v-model.trim
      render: ({ searchParam }) => {
        return (
          <div class="flx-center">
            <el-input vModel_trim={searchParam.minAge} placeholder="最小年龄" />
            <span class="mr10 ml10">-</span>
            <el-input vModel_trim={searchParam.maxAge} placeholder="最大年龄" />
          </div>
        );
      }
    }
  },
  { prop: "idCard", label: "身份证号", search: { el: "input" } },
  { prop: "email", label: "邮箱" },
  { prop: "address", label: "居住地址" },
  {
    prop: "createTime", label: "创建时间",
    //除了表格用具名插槽写法，也可以jsx来自定义headerRender函数定义表头的样式
    headerRender: (scope: HeaderRenderScope<User.ResUserList>) => {
      return (
        <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
          {scope.column.label}
        </el-button>
      );
    },
    width: 180,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },//props为给原生el组件传递的props
      defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 230 }
];

</script>